<?php
/***************************************************************
*
*  (c) 2005-2012 Chi Hoang (info@chihoang.de)
*  All rights reserved
*
***************************************************************/

	// DEFAULT initialization of a module [BEGIN]
unset($MCONF);
require ("conf.php");
require ($BACK_PATH."init.php");
require ($BACK_PATH."template.php");
$LANG->includeLLFile("EXT:ch_raetseltreff/mod_object/locallang.php");
require_once (t3lib_extMgm::extPath ( 'ch_raetseltreff' ) . 'classes/class.tx_ch1_scriptclasses.php');

$BE_USER->modAccess($MCONF,1);	// This checks permissions and exits if the users has no permission for entry.
	// DEFAULT initialization of a module [END]

class tx_ch1_object extends tx_ch1_scriptclasses
{	
	public $identString = 'tx_chraetseltreff';
	public $pageinfo;
	public $newfile;
	public $xajax;
	public $useXajax;
	
	function init()
	{
		global $BE_USER,$LANG,$BACK_PATH,$TCA_DESCR,$TCA,$CLIENT,$TYPO3_CONF_VARS;
	
		session_unset();
		session_start();
		parent::init();
	}

	/*****************************
	 *
	 * General Helper functions
	 *
	 *****************************/

	function loesungen ($number)
	{
		$res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
			'S.title ST, S.*, COUNT( * ) AS matches, P.*',
			'tx_chraetseltreff_user U 
			LEFT JOIN tx_chraetseltreff_spiel S ON U.uid=S.user_id
			LEFT JOIN tx_chraetseltreff_print P ON P.uid=S.print_id
			',
			'S.print_id='.mysql_real_escape_string($_SESSION["uid"]).
			' AND S.kw='.$number.
			' AND U.deleted=0 AND U.hidden=0 AND S.deleted=0 AND S.hidden=0',
			'ST',
			'matches DESC',
			'10'
		);
		
		$path = "../../../../uploads/tx_chraetseltreff/";
		$htmlfilename=$path."filecache.html";
		$pdf = array();
		$c=0;
		
		while ( $b = $GLOBALS [ 'TYPO3_DB' ]->sql_fetch_assoc ( $res ) )
		{
			if ($c==0)
			{
				$title = $b["title"];
				$replyemail = $b["replyemail"];
				$replyname = $b["replyname"];
				$toemail = $b["toemail"];
				$toname = $b["toname"];
				$emailbetreff = $b["emailsubject"];
				$emailbody = $b["emailbody"];
				$c++;
			}
			
			$liste = array();
			
			$innerloop = $GLOBALS['TYPO3_DB']->exec_SELECTquery( "*",
																 "tx_chraetseltreff_user U
																 INNER JOIN tx_chraetseltreff_spiel S ON U.uid=S.user_id",
																 "title=\"".$b['ST']."\"",
																 "",
																 "",
																 ""
																);
			
			while ($d = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($innerloop))
			{
				$liste[$d["email"]]=$d;	
			}
			
			$num = count($liste) >= 200 ? 200 : count($liste);
			$rand_keys = array_rand($liste, $num);
		
			$a = "<html><head></head><body><table>";
			foreach ($rand_keys as $k )
			{
				$a .= "<tr><td>".$liste[$k]["title"]."</td><td>".($liste[$k]["anrede"]==0 ? "Frau" : "Herr")." ".
														$liste[$k]["vorname"]." ".$liste[$k]["name"]."\r\n".
														$liste[$k]["strasse"]." ".$liste[$k]["hausnummer"]."\r\n".
														$liste[$k]["plz"]." ".$liste[$k]["ort"]."</td><td>".
														$liste[$k]["hinweise"]."</td><td>".$liste[$k]["telefon"]."</td></tr>";	
			}
			$a.="</table><body></html>";
			
			$handle = fopen ($htmlfilename, "w+" );                    
			fwrite( $handle, $a );
			fclose ( $handle );
	
			$pdf[$b['ST']] = $path . "Lösungswort ".$b['ST'].".pdf";
			
				// Run HTMLDOC to provide the PDF file to the user...
			$passthru = 'htmldoc -t pdf --quiet --jpeg --webpage --outfile '.'\''.$pdf[$b['ST']].'\' \''.$htmlfilename.'\'';
			passthru ( $passthru );	
		}
		
		if ( $b )
		{
			$needle = array ("###MAGAZIN###", "###KW###");
			$replace = array ($title, $number);
			$emailbetreff=str_replace($needle,$replace,$emailbetreff);
			$body=str_replace($needle,$replace,$body);
			
			$mail = t3lib_div::makeInstance('t3lib_mail_message');
			$mail->setFrom(array($replyemail => $replyname));
			$mail->setTo(array($toemail => $toname));
			$mail->setSubject($betreff);
			$mail->setBody($body);
			$mail->addPart($body);
			
			foreach ($pdf as $k => $filename)
			{
				if (file_get_contents($filename))
				{
					$mail->attach(Swift_Attachment::fromPath($filename));
				}	
			}
			$mail->send();	
		}
	}
	
	/**
	 * Creates the id for dynTabMenus.
	 *
	 * @param	string		$identString: Identification string. This should be unique for every instance of a dynamic menu!
	 * @return	string		The id with a short MD5 of $identString and prefixed "DTM-", like "DTM-2e8791854a"
	 */
	function getDynTabMenuId($identString)
	{
		$id = 'DTM-'.t3lib_div::shortMD5($identString);
		return $id;
	}
	
	/**
	 * Adds items to the ->MOD_MENU array. Used for the function menu selector.
	 */
	function menuConfig()
	{
		global $LANG;
        
		//$this->MOD_MENU = Array (
		//	"function" => Array (
		//		"1" => $LANG->getLL("function1"),
		//		"2" => $LANG->getLL("function2")
		//	)
		//);
		parent::menuConfig();
	}

		// If you chose "web" as main module, you will need to consider the $this->id parameter which will contain the uid-number of the page clicked in the page tree
	/**
	 * Main function of the module. Write the content to $this->content
	 */
	function main()
	{
		global $BE_USER,$LANG,$BACK_PATH,$TCA_DESCR,$TCA,$CLIENT,$TYPO3_CONF_VARS;

		if ( $_GET["SET"]["function"] )
		{
			$this->MOD_SETTINGS["function"] = $_GET["SET"]["function"];
		}
		
		if (($this->id && $access) || ($BE_USER->user["admin"] && !$this->id))
		{
				// Draw the header.
			$this->doc = t3lib_div::makeInstance("mediumDoc");
			$this->doc->backPath = $BACK_PATH;
			
				// Draw the header.
			$this->doc = t3lib_div::makeInstance("mediumDoc");
			$this->doc->backPath = $BACK_PATH;
			$this->doc->form = '<form id="ch_raetseltreff" action="index.php" method="post" enctype="'.
				$GLOBALS['TYPO3_CONF_VARS']['SYS']['form_enctype'].'">';
            
    				// JavaScript
			$this->doc->JScode = $this->doc->wrapScriptTags(
				($this->currentSubScript?'top.currentSubScript=unescape("'.
				 rawurlencode($this->currentSubScript).'");':'').'
					function jumpToUrl(URL)
					{
						document.location = URL;
					}
					
						// Highlighting rows in the page tree:
					function hilight_row(id,highLightID)
					{
						var result = highLightID.search(/Sysfolder/);
						if (result != -1)
						{
							old = $("#pageID").val();
							$("#targetFolder").val(id);
							$("#pageID").val(highLightID);
						} else
						{
							old = $("#catID").val();
							$("#catID").val(highLightID);
							$("#targetCat").val(id);
						}
						if (old)
						{
							$("#"+old).css("background-color","#ffffff");
						}
						$("#"+highLightID).css("background-color","#d0e4c9");
					}
			');
			
			$this->doc->JScode .= $this->doc->getDynTabMenu();

			$this->doc->postCode='
				<script language="javascript" type="text/javascript">
					script_ended = 1;
					if (top.fsMod) top.fsMod.recentIds["web"] = '.intval($this->id).';
				</script>
			';
			
			$headerSection = "";
			$this->content.=$this->doc->startPage($LANG->getLL("title"));
			$this->content.=$this->doc->header($LANG->getLL("title"));
			$this->content.=$this->doc->spacer(5);
			$this->content.=$this->doc->section("",$this->doc->funcMenu($headerSection,
							t3lib_BEfunc::getFuncMenu($this->id,
							"SET[function]",
							$this->MOD_SETTINGS["function"],
							$this->MOD_MENU["function"])));
			$this->content.=$this->doc->divider(5);
			
			// Render content:
			//switch((string)$this->MOD_SETTINGS["function"])
			switch(1)
			{	
					// Gewinnspiel
				case 1:      
				{
					$cmd = t3lib_div::_GET('SLCMD');
					if (!empty($cmd))
					{
						list($uid) = array_keys($cmd['SELECT']['txchvaObject']);
						$_SESSION ["uid"] = $uid;	
					}
					
					if ( !empty($uid) )
					{
						$res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
							'COUNT(*) AS count, U.uid, U.pid, S.print_id, S.uid',
							'tx_chraetseltreff_user U 
							LEFT JOIN tx_chraetseltreff_spiel S ON U.uid=S.user_id',
							'S.print_id='.mysql_real_escape_string($uid).
							' AND U.deleted=0 AND U.hidden=0 AND S.deleted=0 AND S.hidden=0',
							'',
							'',
							''
						);
						
						$rec = $GLOBALS [ 'TYPO3_DB' ]->sql_fetch_assoc ( $res );
						$gesamt = $rec["count"];		
					
						$res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
							'title, COUNT( * ) AS matches',
							'tx_chraetseltreff_user U
							LEFT JOIN tx_chraetseltreff_spiel S ON U.uid=S.user_id',
							'S.print_id='.mysql_real_escape_string($uid).
							' AND U.deleted=0 AND U.hidden=0 AND S.deleted=0 AND S.hidden=0',
							'title',
							'matches DESC',
							'10'
						);
						$c="";
						while ( $rec = $GLOBALS [ 'TYPO3_DB' ]->sql_fetch_assoc ( $res ) )
						{
							$c .= "<tr><td>".$rec["title"]."</td><td>".$rec["matches"]."</td></tr>";	
						}
					}			

					//now, compose TAB menu array for TAB1
					$menuItems[] = array(
					    'label' => $LANG->getLL('f1.tab1'),
					    'content' => '
								<table border="0" cellpadding="1" cellspacing="1" width="100%">
								<tr class="bgColor4">
									<td valign="top"><div id="treeRoot" style="width:360px; height:450px;overflow:auto;background-color:#f1f1f1;margin-right:14px">
									<table border="0" cellspacing="2" cellpadding="2"><tr><td>Gesamtteilnehmeranzahl:</td><td>'.$gesamt.'</td><tr>'.$c.'</table>
								</div></td>
								</tr></table>
					    ',
					    'description' => $LANG->getLL('f1.tab1.description'),
					    'linkTitle' => '',
					    'stateIcon' => 0
					);
					/**** TAB 1 data *****/
					
					if ( !empty($uid) )
					{
						$res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
							'title, COUNT( * ) AS matches',
							'tx_chraetseltreff_user U 
							LEFT JOIN tx_chraetseltreff_spiel S ON U.uid=S.user_id',
							'S.print_id='.mysql_real_escape_string($uid).
							' AND U.deleted=0 AND U.hidden=0 AND S.deleted=0 AND S.hidden=0',
							'title',
							'matches DESC',
							'10'
						);
					
						$a = "<table>";
						while ( $rec = $GLOBALS [ 'TYPO3_DB' ]->sql_fetch_assoc ( $res ) )
						{
							$innerloop = $GLOBALS['TYPO3_DB']->exec_SELECTquery( "*",
																				 "tx_chraetseltreff_user U
																				 INNER JOIN tx_chraetseltreff_spiel S ON U.uid=S.user_id",
																				 "title=\"".$rec['title']."\"",
																				 "",
																				 "",
																				 "100"
																				);
							
							while ($data = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($innerloop))
							{
								$a .= "<tr><td>".$data["title"]."</td><td>".($data["anrede"]==0 ? "Frau" : "Herr")." ".
																$data["vorname"]." ".$data["name"]."\r\n".
																$data["strasse"]." ".$data["hausnummer"]."\r\n".
																$data["plz"]." ".$data["ort"]."</td><td>".
																$data["hinweise"]."</td><td>".$data["telefon"]."</td></tr>";
							}
						}
						$a .= "</table>";
					}
					
				
						//now, compose TAB menu array for TAB2
					$menuItems[] = array(
					    'label' => $LANG->getLL('f1.tab2'),
					   	'content' => '
							<table border="0" cellpadding="1" cellspacing="1" width="100%">
							<tr class="bgColor4">
								<td valign="top"><div id="treeRoot" style="width:420px; height:450px;overflow:auto;background-color:#f1f1f1;margin-right:14px">'.$a.
							'</div></td>
							</tr>
							<tr><td align="right">
							<input type="hidden" id="submit" name="submit" value="email">
							<input type="submit" value="Submit"></td></tr>
							</table>
					    ',
					    'description' => $LANG->getLL('f1.tab2.description'),
					    'linkTitle' => '',
					    'stateIcon' => 0
					);
				}
				break;
			
			
				//case 2:
				//{
				//	
				//	
				//	
				//}
				//break;
			}
			
				// finally, print out the whole tabmenu
			$content = $this->doc->getDynTabMenu($menuItems, $this->identString,0,'',40,'','', ( empty($_SESSION["tab"]) ? "1" : $_SESSION["tab"]) );
						
			$this->content .= $content."</form>";

			//xdebug_break();
			if ($_POST ["submit"] == 'email' && !empty($_SESSION["uid"]) )
			{
				$q = "DELETE u1 From tx_chraetseltreff_user u1 JOIN tx_chraetseltreff_user u2 USING (email) WHERE u1.tstamp < u2.tstamp"; 
				$res = $GLOBALS['TYPO3_DB']->sql_query($q);
				$q = "DELETE s From tx_chraetseltreff_spiel s WHERE user_id NOT IN (SELECT uid from tx_chraetseltreff_user WHERE uid is not null)";
				$res = $GLOBALS['TYPO3_DB']->sql_query($q);
				
				$this->loesungen((int)date("W"));
				$this->loesungen((int)date("W")+1);
				$this->loesungen((int)date("n"));
				$this->loesungen((int)date("n")+1);
			}
			
			// ShortCut
			if ($BE_USER->mayMakeShortcut())
			{
				$this->content.=$this->doc->spacer(20).$this->doc->section("",
						$this->doc->makeShortcutIcon("id",
						implode(",",array_keys($this->MOD_MENU)),
						$this->MCONF["name"]));
			}

			$this->content.=$this->doc->spacer(10);
			$this->content = $this->doc->insertStylesAndJS($this->content);
            
		} else
		{
				// If no access or if ID == zero
			$this->doc = t3lib_div::makeInstance("mediumDoc");
			$this->doc->backPath = $BACK_PATH;

			$this->content.=$this->doc->startPage($LANG->getLL("title"));
			$this->content.=$this->doc->header($LANG->getLL("title"));
			$this->content.=$this->doc->spacer(5);
			$this->content.=$this->doc->spacer(10);
		}
	}

	/**
	 * Prints out the module HTML
	 */
	function printContent()
	{
		$this->content.=$this->doc->endPage();
		echo $this->content;
	}
}

if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['ext/ch_raetseltreff/mod_object/index.php'])
{
	include_once($TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['ext/ch_raetseltreff/mod_object/index.php']);
}

	// Make instance:
$SOBE = t3lib_div::makeInstance('tx_ch1_object');
$SOBE->init();

	// Include files?
foreach($SOBE->include_once as $INC_FILE) include_once($INC_FILE);

$SOBE->main();
$SOBE->printContent();

?>